package com.zsy.springframework.beans.facotry.beanfactory;

import com.zsy.springframework.beans.facotry.exception.BeansException;
import com.zsy.springframework.beans.facotry.jiekou.one.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//从缓存中取beanfactory对象，然后使用
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
    //就是存放factorybean缓存的地方
    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>();

    protected Object getCachedObjectForFactoryBean(String beanName) {
        Object object = this.factoryBeanObjectCache.get(beanName);
        return (object != NULL_OBJECT ? object : null);
    }

    protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName) {
        if (factory.isSingleton()) {
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (object == null) {
                object = doGetObjectFromFactoryBean(factory, beanName);
                this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
            }
            return (object != NULL_OBJECT ? object : null);
        } else {
            return doGetObjectFromFactoryBean(factory, beanName);
        }
    }


    private Object doGetObjectFromFactoryBean(FactoryBean factory, String name) {
        try {
            return factory.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean threw exception on object[" + name + "] creation", e);
        }
    }


}
